<template>
  <div class="registration-list">
    <section class="page-back">
      <router-link to="/events">活动赛事 > </router-link>
      <router-link to="/events/school"> 校园活动 > </router-link>
      <router-link :to="{path: '/events/activitiesDetails', query: {id: activityId}}"> {{infoDetail.name}} > </router-link>
      <span> 报名名单 </span>
    </section>
    <section class="registration-container">
      <div class="title-row">
        <h3>{{infoDetail.name}}</h3>
        <div class="btns-div">
          <el-tag size="mini">{{registrationData.length}} / {{infoDetail.quota}}</el-tag>
          <el-button type="primary" class="output-btn" @click="getAllData">导出名单</el-button>
        </div>
      </div>
      <div class="project-info">
        <template>
          <div class="zh-table-contents" v-loading="loading.status" :element-loading-text="loading.txt">
            <el-table :data="registrationData" border>
              <el-table-column prop="user_name" label="用户" align="center" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="user_number" label="账号" align="center" show-overflow-tooltip>
              </el-table-column>
              <el-table-column label="学段年级班级" align="center" show-overflow-tooltip>
                <template slot-scope="scope">{{ scope.row.org_name==''?'未绑定':scope.row.org_name }}</template>
              </el-table-column>
              <el-table-column prop="role_name" label="角色" align="center" show-overflow-tooltip>
              </el-table-column>
              <!-- 自定义报名部分 -->
                            <el-table-column
                                v-for="(col, inx) in customCols"
                                :key="inx"
                                :prop="col.prop"
                                :label="col.label"
                                align="center"
                                show-overflow-tooltip
                            >
                            </el-table-column>
              <el-table-column prop="status_txt" label="状态" align="center" show-overflow-tooltip>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button @click="goDetail(scope.row)" type="text">详情</el-button>
                  <el-button v-if="scope.row.status==0" @click="passRow(scope.row)" type="text">通过</el-button>
                  <el-button v-if="scope.row.status==0" @click="rejectRow(scope.row)" type="text" class="delete-button">拒绝</el-button>
                  <el-button v-if="scope.row.status==2" @click="checkReason(scope.row)" type="text">理由</el-button>
                  <el-button v-if="scope.row.status==2" @click="delRow(scope.row.id)" type="text">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </div>
    </section>
    <el-dialog class="registry-dialog" title="报名信息" :visible.sync="registryVisible" width="550px">
      <el-form ref="registryInfo" :model="registryInfo" label-width="120px" label-position="left">
        <el-form-item label="用户名:">
          {{registryInfo.user_name}}
        </el-form-item>
        <el-form-item label="账号:">
          {{registryInfo.user_number}}
        </el-form-item>
        <el-form-item label="学段年级班级:" v-if="registryInfo.org_name">
          {{registryInfo.org_name}}
        </el-form-item>
        <el-form-item label="角色:">
          {{registryInfo.role_name}}
        </el-form-item>
        <el-form-item label="联系方式:">
          {{registryInfo.telphone}}
        </el-form-item>
      </el-form>
      <div class="form-footer-btns">
        <el-button type="primary" @click="registryVisible = false">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog class="registry-dialog" title="拒绝" :visible.sync="rejectVisible" width="550px">
      <el-form ref="rejectInfo">
        <el-form-item label="">
          <el-input type="textarea" placeholder="请输入拒绝理由" v-model="rejectReason" maxlength="140" resize="none" :autosize="{ minRows: 8}" show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <div class="form-footer-btns">
        <el-button type="primary" @click="approve(2)">确定</el-button>
        <el-button @click="rejectVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog class="registry-dialog" title="拒绝理由" :visible.sync="checkVisible" width="550px">
      <el-form ref="rejectInfo">
        <el-form-item label="">
          {{rejectInfo}}
        </el-form-item>
      </el-form>
      <div class="form-footer-btns">
        <el-button type="primary" @click="checkVisible = false">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import XLSX from 'xlsx';
import FileSaver from 'file-saver';
export default {
  data() {
    return {
      activityId: this.$route.query.id,
      infoDetail: [],//活动信息
      selected: [], // 选中的数据
      loading: {
        status: false,
        txt: '获取数据...'
      },

      registrationData: [],//名单数据
       customCols: [], //自定义部分标题数据
      // 分页：
      page_index: 1,
      page_size: 10,
      total_number: 0,
      registryVisible: false,//报名信息弹窗
      registryInfo: {},//报名信息
      rejectId: "",
      rejectVisible: false,//拒绝弹窗
      rejectReason: "",//拒绝理由
      checkVisible: false,//拒绝理由弹窗
      rejectInfo: "",//查看拒绝详情
    };
  },
  created() {
    this.getDetail();
    this.getRegistration();
  },
  mounted() {

  },
  computed: {

  },
  methods: {
    /**
* 获取活动详情 
*/
    getDetail() {
      let success = (res => {
        this.infoDetail = res.data;
      })
      const params = {
        id: this.$route.query.id
      }
      this.$ajax.get('api/competition/activity', { params, func: { success: success } });
    },
    /**
* 获取报名名单 
*/
    getRegistration() {
      let success = res => {
       if (res.data.data.length > 0) {
                    let _data = res.data.data;
                    let registration_information =
                        res.data.data[0].registration_information;
                    // 获取自定义表头
                    registration_information.forEach((item, index) => {
                        let col = {};
                        col.prop = "registration" + index;
                        col.label = item.name;
                        this.customCols.push(col);
                    });
                    // table数组添加跟表头对应的键值对
                    for (let i = 0; i < _data.length; i++) {
                        for (let j = 0; j < _data[i].information.length; j++) {
                            _data[i]["registration" + j] =
                                _data[i].information[j].value;
                        }
                    }
                    this.registrationData = _data;
                }
      };
      this.$ajax({
        url: "api/competition/activity_user",
        method: "get",
        params: {
          page_index: this.page_index,
          page_size: this.page_size,
          competition_id: this.$route.query.id
        },
        func: {
          success: success
        }
      });
    },

    //详情
    goDetail(val) {
      this.registryVisible = true;
    //   console.log(val)
      this.registryInfo = val;
    },
    //通过
    passRow(val) {
      this.rejectId = val.id;
      this.approve(1);
    },
    // 查看拒绝理由
    checkReason(val) {
      this.checkVisible = true;
      this.rejectInfo = val.reason;
    },
    // 拒绝
    rejectRow(val) {
      this.rejectReason = "";
      this.rejectId = val.id;
      this.rejectVisible = true;
    },

    /**
* 活动名单审批
* @param {Number} status 1：通过；3：拒绝
*/
    approve(status) {
      let success = res => {
        this.$message.success(res.msg);
        this.getRegistration();
        this.rejectVisible = false;
      };
      let fail = res => {
        this.$message.error(res.msg);
      };
      this.$ajax({
        url: "api/competition/activity_user_approve",
        method: "post",
        data: {
          id: this.rejectId,
          status: status,
          reason: status == 1 ? "" : this.rejectReason
        },
        func: {
          success: success,
          fail: fail
        }
      });
    },
    // 删除
    delRow(id) {
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "confirm-them"
      })
        .then(() => {
          this.sureDel(id);
        })
        .catch(() => { });

    },
    // 确定删除
    sureDel(id) {
      let success = res => {
        this.$message.success(res.msg);
        this.getRegistration();
      };
      let fail = res => {
        this.$message.error(res.msg);
      };
      this.$ajax({
        url: "api/competition/activity_user",
        method: "delete",
        params: {
          id: id
        },
        func: {
          success: success,
          fail: fail
        }
      });
    },
    /**
  * 获取全部数据后导出
  */
    async getAllData() {
      if (this.total_number <= this.page_size) {
        this.exportExcel(this.registrationData);
      } else {
        let All = [];
        let len = Math.ceil(this.total_number / 100);
        let success = (res => {
            console.log(res)
          All = [...All, ...res.data.data.data];
        })

        for (let i = 1; i <= len; i++) {
          let params = {
            competition_id: this.$route.query.id,
            page_index: i,
            page_size: 100,
          }

          await this.$ajax.get('api/competition/activity_user', { params: params, func: { success: success } });
        }
        this.exportExcel(All);
      }
    },
    /**
     * 导出Excel表
     * @param {Array} allData 全部数据
     */
    exportExcel(allData) {
      if (allData.length === 0) {
        this.$message.warning("导出的数据为空！");
        return false;
      }

      let exportList = [];
      const defaultCellStyle = { font: { name: "Verdana", sz: 14, color: "FF00FF88" }, fill: { fgColor: { rgb: "FFFFAA00" } } };
      const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary', defaultCellStyle: defaultCellStyle, showGridLines: false };
      const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };


      for (let i = 0; i <= allData.length - 1; i++) {
        // 每个名单表格中必有的选项
        let baseObj = {
          用户: allData[i].user_name,
          账号: allData[i].user_number,
          学段年级班级:
            allData[i].org_name == "" ? "未绑定" : allData[i].org_name,
          角色: allData[i].role_name,
          状态: allData[i].status_txt
        };
        //表格中自定义项(每个报名自定义部分)
        let obj = {};
        allData[i].information.forEach((item, inx) => {
          let keyn = JSON.parse(item).name;
          let valn = JSON.parse(item).value;
          obj[keyn] = valn;
          // 固定选项和自定义选项合并到一个对象，丢进exportList数组
          exportList[i] = Object.assign(baseObj, obj);
        });
      }
      // console.log(exportList, 1);
      wb.Sheets["Sheet1"] = XLSX.utils.json_to_sheet(exportList);
      wb.Sheets["Sheet1"]["!cols"] = [
        {
          wpx: 110
        },
        {
          wpx: 110
        },
        {
          wpx: 120
        },
        {
          wpx: 110
        },
        {
          wpx: 80
        },
        {
          wpx: 140
        },
        {
          wpx: 140
        },
        {
          wpx: 140
        },
        {
          wpx: 140
        },
        {
          wpx: 140
        },
        {
          wpx: 140
        }
      ];

      //创建二进制对象写入转换好的字节流
      let tmpDown = new Blob([this.str2Buffer(XLSX.write(wb, wopts))], { type: "application/octet-stream" });
      FileSaver.saveAs(tmpDown, `报名名单-表格.xlsx`);
    },
    /**
     * 字符串转类型化数组
     * @param {String} str 字符串
     */
    str2Buffer(str) {
      if (typeof ArrayBuffer !== 'undefined') {
        let buf = new ArrayBuffer(str.length);
        let view = new Uint8Array(buf);

        for (let i = 0; i != str.length; i += 1) {
          view[i] = str.charCodeAt(i) & 0xFF;
        }
        return buf;
      } else {
        let buf = new Array(str.length);

        for (let i = 0; i != str.length; i += 1) {
          buf[i] = str.charCodeAt(i) & 0xFF;
        }
        return buf;
      }
    },
  },
};
</script>
<style lang="scss">
%ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.page-back {
  font-size: 14px;
  padding: 5px 0 25px;
  a:nth-child(1) {
    color: #333;
  }
  span {
    color: #3f3f3f;
  }
}
.registration-container {
  background-color: #fff;
  padding: 60px 60px 80px;
  .title-row {
    height: 32px;
    line-height: 32px;
    text-align: center;
    margin-bottom: 50px;
    padding: 0 180px;
    position: relative;
    h3 {
      font-size: 22px;
      font-weight: bold;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .btns-div {
      display: inline-block;
      position: absolute;
      right: 0;
      top: 0;
      .output-btn {
        padding: 0;
        width: 86px;
        height: 32px;
        margin-left: 20px;
      }
    }
  }
}
.registry-dialog {
  .form-footer-btns {
    text-align: center;
    .el-button {
      padding: 0;
      width: 68px;
      height: 30px;
    }
  }
}
.el-table {
  th {
    padding: 6px 0;
  }
  td {
    padding: 0;
  }
  th {
    background-color: #f2f2f2;
    border: 1px solid #f2f2f2;
    padding: 6px 0;
  }
}
</style>